package com.xxg.renrensearch.schedule;

import com.xxg.renrensearch.cache.StatisticsCache;
import com.xxg.renrensearch.init.RenrenShopProductsInit;
import com.xxg.renrensearch.init.RenrenShopShopInit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 每小时的定时任务
 *
 * @author xuxiaogang
 * @date 2021-11-30
 */
@Configuration
@EnableScheduling
public class ScheduleTask {
    private final Logger logger = LoggerFactory.getLogger(ScheduleTask.class);
    private final RenrenShopShopInit renrenShopShopInit;
    private final RenrenShopProductsInit renrenShopProductsInit;
    private final SyncData syncData;
    private final StatisticsCache statisticsCache;
    private String syncDate;

    /**
     * 锁对象，让定时任务有序执行
     */
    private static final ReentrantLock LOCK = new ReentrantLock();

    public ScheduleTask(RenrenShopShopInit renrenShopShopInit, RenrenShopProductsInit renrenShopProductsInit,
                        SyncData syncData, StatisticsCache statisticsCache) {
        this.renrenShopShopInit = renrenShopShopInit;
        this.renrenShopProductsInit = renrenShopProductsInit;
        this.syncData = syncData;
        this.statisticsCache = statisticsCache;
        syncDate = this.renrenShopShopInit.getSyncDateStr();
    }

    /**
     * 每个整点执行的数据同步任务
     */
    @Scheduled(cron = "0 0 0-23 * * ?")
    public void hourTask() {
        LOCK.lock();
        try {
            logger.info("hourTask start");
            renrenShopShopInit.syncData();
            renrenShopProductsInit.syncData();
            syncDate = renrenShopShopInit.getSyncDateStr();
            statisticsCache.cleanCache();
            logger.info("hourTask end");
        } finally {
            LOCK.unlock();
        }
    }

    /**
     * 每隔30秒执行的数据同步任务
     */
    @Scheduled(cron = "5/30 * * * * ?")
    public void minuteTask() {
        if (LOCK.tryLock()) {
            try {
                logger.info("minuteTask start");
                syncData.syncDataByTime(syncDate);
                syncDate = syncData.getSyncDateStr();
                statisticsCache.cleanCache();
                logger.info("minuteTask end");
            } finally {
                LOCK.unlock();
            }
        } else {
            logger.info("hourTask is running, skip minuteTask");
        }
    }
}
